﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Web
{
	/// <summary>
	/// - Cau truc cua thong tin quan ly tren cookies (Not persistent cookies)
	///  + Name: Class name + UserID
	/// - Subkeys:
	///  + Name: chua id cua cua control can luu du lieu
	///  + Value: chua gia tri cua control do duoi dang chuoi
	/// </summary>
	/// <remarks></remarks>
	public class CookiesManager
	{
		#region Static Methods

		public static void Update(string cookiesName, string controlID, string value)
		{
			HttpCookie cookies = null;

			if ((HttpContext.Current.Request.Cookies[cookiesName] != null))
            {
				cookies = HttpContext.Current.Request.Cookies[cookiesName];
			} else 
            {
				cookies = new HttpCookie(cookiesName);
			}

			cookies.Values[controlID] = HttpContext.Current.Server.UrlEncode(value);
			HttpContext.Current.Response.Cookies.Add(cookies);
		}

		public static string GetValue(string cookiesName, string controlID)
		{
			string result = null;

			if ((HttpContext.Current.Request.Cookies[cookiesName] != null) && (HttpContext.Current.Request.Cookies[cookiesName].Values[controlID] != null)) 
            {
				result = HttpContext.Current.Server.UrlDecode(HttpContext.Current.Request.Cookies[cookiesName].Values[controlID]);
			}
			return result;
		}

		private static void DeleteCookies(string cookiesName)
		{
			if ((HttpContext.Current.Request.Cookies[cookiesName] != null)) 
            {
				HttpCookie cookies = null;
				cookies = HttpContext.Current.Request.Cookies[cookiesName];
				cookies.Expires = DateTime.Now.AddDays(-1);

				HttpContext.Current.Response.Cookies.Add(cookies);
			}
		}

		public static void DeleteAllCookies()
		{
			for (int i = 0; i <= HttpContext.Current.Request.Cookies.Count - 1; i++) 
            {
				DeleteCookies(HttpContext.Current.Request.Cookies[i].Name);
			}
		}

		#endregion

	}
}
